import { useState } from "react";
import IconFont from "../IconFont";
import "./index.scss";
import { HFile } from "../../api/modules/file";


interface FileUpload {
  // 必选
  required?: boolean;
  // 最大数量
  maxLen?: number;
  // 是否预览
  isPreview?: boolean;
  // 多选
  isMultipleChoices?: boolean;
  // 切换事件
  onChange?: (file: FileItem, files: FileItem[]) => void;
}


interface FileItem {
  id: string;
  name: string;
  original_name: string;
  suffix: string;
  size: number;

  // 渲染使用字段
  source?: File
  isNew?: boolean;
  preview_path?: string;
}

/**
 * 文件上传组件
 * @returns 
 */
const FileUpload: React.FC<FileUpload> = ({ onChange }) => {
  // 上传后的文件列表
  const [uploadList, setUploadList] = useState<FileItem[]>([]);

  /**
   * 上传文件
   * @param file 
   */
  const uploadFile = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    const result = await HFile.uploadFile<FileItem>('文件上传', formData);
    result.source = file;
    result.isNew = true;
    result.preview_path = (await fileToBase64(file)) || '';
    const newFileList = [...uploadList, result];
    setUploadList(newFileList);
    console.log(result, uploadList)
    setTimeout(() => {
      if (onChange) {
        onChange(result, newFileList);
      }
    }, 200);
  }

  /**
   * 文件转base64
   * @param file 
   * @returns 
   */
  const fileToBase64 = (file: File): Promise<string | null> => {
    return new Promise(resolve => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = () => resolve(null);
    })

  } 

  /**
   * file事件
   * @param data 
   */
  const onFileControlChange = (data: any) => {
    const files = data.target.files;
    console.log(files);
    uploadFile(files[0]);
  }

  return <div className="file-upload__container">
    <div className="select-file__control">
      <IconFont name="jia1" size="20px" />
      <input type="file" onChange={onFileControlChange} />
    </div>

    {/* 已上传的文件列表 */}
    <ul className="upload__list">
      {
        uploadList.map(file => {
          return <li key={file.id} className="upload__item">
            <div className="file-cover"></div>
            <img className="file-img" src={file.preview_path} alt="" />
            <p className="file-name">{ file.name }</p>
          </li>
        })
      }
    </ul>
  </div>
};


export default FileUpload;